package com.teamone.etl.systemsettings.utils;

import org.springframework.beans.factory.annotation.Value;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author huaiyu
 * @create 2021/1/24 22:21
 */
public class GetIpUtils {

    /**
     * txt|jsonp|xml
     */
    public static String DATATYPE="jsonp";

    private static Integer TWO_HUNDRED=200;

    @Value("${ip.token}")
    private static String IP_TOKEN;

    public static String get(String urlString,String token) {
        try {
            URL url = new
                    URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setReadTimeout(5 * 1000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("token",token);
            int responseCode = conn.getResponseCode();
            if (responseCode == TWO_HUNDRED) {
                StringBuilder builder = new StringBuilder();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(),"utf-8"));
                for (String s = br.readLine(); s != null; s = br
                        .readLine()) {
                    builder.append(s);
                }
                br.close();
                return builder.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String queryIp(String ip){
        String url="https://api.ip138.com/ip/?ip="+ip+"&datatype="+DATATYPE;
        String token= GetIpUtils.IP_TOKEN;
        return get(url,token);
    }



}
